package com.muyun.data.modeler.infrastructure.general.config;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * 参数验证框架配置
 *
 * @author muyun12
 * @date 2020-12-21 22:54:38
 * @since 0.1.0
 */
@Configuration
public class ValidationConfig {

    @Bean
    public Validator getValidator() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        // 读取配置文件的编码格式
        source.setDefaultEncoding("utf-8");
        // 缓存时间，-1表示不过期
        source.setCacheMillis(-1);
        // 配置文件前缀名，设置为Messages,那你的配置文件必须以Messages.properties/Message_en.properties
        source.setBasename("i18n/ValidationMessages");
        // LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        // MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
        // factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
        // factoryBean.setValidationMessageSource(source);
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
                .messageInterpolator(new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(source)))
                .failFast(true).buildValidatorFactory();
        return validatorFactory.getValidator();
        // return factoryBean;
    }
}
